package com.qf.blog.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;

@RestController
public class CaptchaController {
    @Autowired
    private DefaultKaptcha captchaGenerator;
    @Autowired
    private RedisTemplate redisTemplate;
    @RequestMapping("/captcha")
    public void generateCaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 生成验证码
        String captchaText = captchaGenerator.createText();
        // 将验证码存储到Session或缓存中
        redisTemplate.opsForValue().set("captchaText", captchaText);
        HttpSession session = request.getSession(); session.setAttribute("captcha", captchaText);
        // 生成验证码图片
        BufferedImage captchaImage = captchaGenerator.createImage(captchaText);
        // 将验证码图片写入响应流
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(captchaImage, "jpg", outputStream);
        outputStream.flush();
        outputStream.close();
    }
}

